package geowiki.dataThread;

import geowiki.data.Link;
import geowiki.data.Place;
import geowiki.data.PlacemakerPlaceExtractor;
import geowiki.data.YQLLinkExtractor;
import geowiki.utils.WikipediaUtils;

import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;

public class PlacesExtractionThread extends Thread {

	protected PlacesExtractionThreadTestApp app;
	protected List<Place> places;
	protected Link link;
        protected String url;

	public PlacesExtractionThread(PlacesExtractionThreadTestApp app, Link link) {
		this.app = app;
		this.link = link;
		PApplet.println("Started thread for " + link.url);
	}

	public void run() {


                List<Place> places = loadPlacesViaPlacemakerFromURL(link.url);

                link.storePlaceMarkers(places);
		PApplet.println("Stored " + places.size() + " places as markers for " + link.url);

	}

	public List<Place> loadPlacesViaPlacemakerFromURL(String url) {
		List<Place> allPlaces = new ArrayList<Place>();

		YQLLinkExtractor linkExtractor = new YQLLinkExtractor(app);

		if (url.startsWith("/wiki")) {
			String fullURL = WikipediaUtils.getFullURLFromLink(url);
			String[] paragraphs = linkExtractor.getMainParagraphs(fullURL);

			PlacemakerPlaceExtractor placeExtractor = new PlacemakerPlaceExtractor(app);
			for (int i = 0; i < paragraphs.length; i++) {
				PApplet.println("Getting places for " + i + ". p");
				List<Place> places = placeExtractor.getPlaces(paragraphs[i]);
				PApplet.println("\tplaces=" + places);
				allPlaces.addAll(places);
			}
		}
		return allPlaces;
	}

}
